import http from '@/utils/http'

export const vocabularySearchMixin = {
  data() {
    return {
      searchTerm: '',
      searchResults: {},
      searchedWordDetail: null,
      loading: false,
      error: null,
      // 单词详情相关
      showWordDetailDialog: false,
      selectedWord: null,
      audio: null,
      // 最近搜索的单词
      recentSearches: []
    }
  },
  computed: {
    hasSearchedWordExamples() {
      if (!this.searchedWordDetail || !this.searchedWordDetail.meanings) return false;
      return this.searchedWordDetail.meanings.some(meaning => meaning.examples && meaning.examples.length > 0);
    }
  },
  mounted() {
    // 从localStorage加载最近搜索的单词
    this.loadRecentSearches()
  },
  methods: {
    /**
     * 替换高亮词汇
     * @param gotWord 返回的单词
     * @param queryingWord 被查询单词
     */
    styleWord(gotWord, queryingWord, option) {
      // 将orgWord中的每个字符，如果出现在word，替换为<span class="highlight">字符</span>
      const opt = option || {};
      opt['font-style'] = 'italic';
      opt.color = opt.color || 'red';

      let styleType = 0;
      if (gotWord.indexOf(queryingWord) >= 0) {
        styleType = 1;
      }
      if (opt.fullWord === true) {
        styleType = 1;
      }

      if (styleType === 1) {
        return gotWord.replaceAll(queryingWord, `<span style="font-style: ${opt['font-style']};color:${opt.color};">${queryingWord}</span>`);
      }
      const defaultRes = gotWord.split('').map(char => {
        if (queryingWord.includes(char)) {
          return `<span style="font-style: ${opt['font-style']};color:${opt.color};">${char}</span>`
        }
        return char
      }).join('');
      if (gotWord.length <= 3) {
        return defaultRes;
      }
      function customReplace(gw, qw, num, startOrEnd) {
        let newKeyStr = "";
        if (startOrEnd === 'start') {
          newKeyStr = qw.substr(num);
        }
        else {
          newKeyStr = qw.substring(0, qw.length - num);
        }
        return gw.replace(new RegExp(newKeyStr, 'g'), `<span style="font-style: ${opt['font-style']};color:${opt.color};">${newKeyStr}</span>`)
      }

      for (let i = 0; i < 3; i++) {
        if (gotWord.indexOf(queryingWord.substr(i)) > -1) { return customReplace(gotWord, queryingWord, i, "start"); }
        if (gotWord.indexOf(queryingWord.substring(0, queryingWord.length - i)) > -1) { return customReplace(gotWord, queryingWord, i, "end"); }
      }
      return defaultRes;
    },
    async performSearch() {
      if (!this.searchTerm.trim()) {
        this.searchResults = {}
        this.searchedWordDetail = null
        return
      }

      this.loading = true
      this.error = null
      this.searchedWordDetail = null

      try {
        const [similarResponse, prefixResponse, suffixResponse, containsResponse, wordDetailResponse] = await Promise.all([
          http.get(`/advance-search/similar/${this.searchTerm}`),
          http.get(`/advance-search/startswith/${this.searchTerm}`),
          http.get(`/advance-search/endswith/${this.searchTerm}`),
          http.get(`/advance-search/contains/${this.searchTerm}`),
          http.get(`/vocabulary/word/${this.searchTerm}`).catch(err => {
            console.warn('Failed to fetch word detail:', err);
            return null;
          })
        ])

        this.searchResults = {
          similar: similarResponse.words || [],
          prefix: prefixResponse.words || [],
          suffix: suffixResponse.words || [],
          contains: containsResponse.words || []
        }

        this.searchedWordDetail = wordDetailResponse

        // 只有当搜索有结果时才添加到最近搜索列表
        if (wordDetailResponse) {
          this.addRecentSearch(this.searchTerm.trim())
        }

        this.loading = false
      } catch (err) {
        this.error = '搜索失败，请稍后重试'
        console.error(err)
        this.loading = false
      }
    },

    // 添加最近搜索的单词
    addRecentSearch(word) {
      // 移除重复项
      const index = this.recentSearches.indexOf(word)
      if (index > -1) {
        this.recentSearches.splice(index, 1)
      }

      // 将单词添加到列表开头
      this.recentSearches.unshift(word)

      // 限制最多显示10个最近搜索的单词
      if (this.recentSearches.length > 10) {
        this.recentSearches.pop()
      }

      // 保存到localStorage
      this.saveRecentSearches()
    },

    // 保存最近搜索的单词到localStorage
    saveRecentSearches() {
      try {
        localStorage.setItem('vocabularyRecentSearches', JSON.stringify(this.recentSearches))
      } catch (e) {
        console.error('Failed to save recent searches to localStorage:', e)
      }
    },

    // 从localStorage加载最近搜索的单词
    loadRecentSearches() {
      try {
        const saved = localStorage.getItem('vocabularyRecentSearches')
        if (saved) {
          this.recentSearches = JSON.parse(saved)
        }
      } catch (e) {
        console.error('Failed to load recent searches from localStorage:', e)
      }
    },

    // 搜索最近的单词
    searchRecentWord(word) {
      this.searchTerm = word
      this.performSearch()
    },

    showWordDetail(word) {
      this.selectedWord = word
      this.showWordDetailDialog = true
    },

    closeWordDetail() {
      this.showWordDetailDialog = false
      this.selectedWord = null
    },

    playPronunciation() {
      if (this.searchedWordDetail && this.searchedWordDetail.pronunciation) {
        if (this.audio) {
          this.audio.pause();
        }

        this.audio = new Audio(`data:audio/mp3;base64,${this.searchedWordDetail.pronunciation}`);
        this.audio.play();
      }
    },

    // 移除单个最近搜索记录
    removeRecentSearch(index) {
      this.recentSearches.splice(index, 1);
      this.saveRecentSearches();
    }
  },
  beforeUnmount() {
    if (this.audio) {
      this.audio.pause();
      this.audio = null;
    }
  }
}